package com.chijun.mform.create.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.chijun.mform.FormBuilder;
import com.chijun.mform.R;
import com.chijun.mform.create.dialog.IGetServerPersonResult;
import com.chijun.mform.create.dialog.ISelectFormIcon;
import com.chijun.mform.create.dialog.ISelectProcessPerson;
import com.chijun.mform.create.dialog.SelectFormIconDialog;
import com.chijun.mform.create.dialog.SelectPersonNewDialog;
import com.chijun.mform.create.mode.Form;
import com.chijun.mform.create.mode.FormAdmin;
import com.chijun.mform.create.mode.FormConfig;
import com.chijun.mform.create.mode.FormFilled;
import com.chijun.mform.create.mode.FormGroup;
import com.chijun.mform.create.mode.FormIcon;
import com.chijun.mform.create.mode.FormUser;
import com.example.ccj.b.c.custom.tree.TreeMode;
import com.example.ccj.b.f.BaseFragment;
import com.example.ccj.u.ActivityUtils;
import com.example.ccj.u.ImageUtils;
import com.example.ccj.u.StringUtils;
import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 表单基础信息Fragment
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2025/1/13 12:07
 */
public class WriteBaseInformationFragment extends BaseFragment {

    private TextView mEtGroup;
    private ImageView icon;
    private final Form form;
    private Context context;
    private List<FormGroup> formGroupList;
    private List<FormIcon> formIconList;
    private final FormConfig formConfig;
    private TextView canSubmitPerson;
    private TextView formAdmin;
    private ProgressBar sAdminLoading,sCanSubmitLoading;
    private RadioGroup visibleStatus;       //可见状态
    private RadioGroup saveModelPosition;   //保存方式

    public WriteBaseInformationFragment(FormConfig formConfig){
        this.formConfig = formConfig;
        this.form = formConfig.getForm();
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_form_write_base_information,container,false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle bundle) {
        super.onViewCreated(view, bundle);
        this.context = view.getContext();

        formGroupList = FormBuilder.getInstance().getFormGroupList();
        formIconList = FormBuilder.getInstance().getFormIconList();

        EditText mEtName = view.findViewById(R.id.activity_form_write_base_information_name);
        mEtGroup = view.findViewById(R.id.activity_form_write_base_information_group);
        EditText mEtNotes = view.findViewById(R.id.activity_form_write_base_information_notes);
        icon = view.findViewById(R.id.activity_form_write_base_information_icon);
        canSubmitPerson = view.findViewById(R.id.activity_form_write_base_information_can_submit);
        formAdmin = view.findViewById(R.id.activity_form_write_base_information_admin);
        sAdminLoading = view.findViewById(R.id.select_admin_loading);
        sCanSubmitLoading = view.findViewById(R.id.select_can_submit_loading);
        visibleStatus = view.findViewById(R.id.activity_form_write_base_information_visible_status);
        saveModelPosition = view.findViewById(R.id.activity_form_write_base_information_save_model_position);


        if (!StringUtils.isEmpty(form.name)) mEtName.setText(form.name);
        if (!StringUtils.isEmpty(form.notes)) mEtNotes.setText(form.notes);

        //表单图标
        if (form.icon > 0) {
            for (FormIcon formIcon : formIconList) {
                if (formIcon.id == form.icon) {
                    ImageUtils.loadImage(context,formIcon.url,icon);
                    break;
                }
            }
        } else {
            ImageUtils.loadImage(context,"https://form-icon-1302729481.cos.ap-beijing.myqcloud.com/icon_38.png",icon);
            form.icon = 38;
        }

        //表单类型
        if (form.groupId != 0) {
            for (FormGroup formGroup : FormBuilder.getInstance().getFormGroupList()) {
                if (formGroup.id == form.groupId) {
                    mEtGroup.setText(formGroup.name);
                    break;
                }
            }
        }

        //表单可提交的人员及部门
        setCanSubmit();

        //设置表单管理员
        setAdmin();

        mEtName.addTextChangedListener(writeFormName);      //表单名称改变事件
        mEtNotes.addTextChangedListener(writeFormNotes);    //表单备注改变事件
        mEtGroup.setOnClickListener(selectFormGroup);       //表单类型选择事件
        icon.setOnClickListener(selectIcon);                //表单图标改变事件
        canSubmitPerson.setOnClickListener(v->getCanSubmitPerson());  //选择可见人员
        formAdmin.setOnClickListener(v->getAdmin());        //选择管理员

        handleVisibleStatus(view);  //处理可见方式
        handleSaveModelPosition(view);//处理表单模型保存方式
    }

    /**
     * 处理表单的可见状态
     * @param view view
     */
    private void handleVisibleStatus(View view){
        //加载原始或者默认数据
        RadioButton radioButton;
        if (formConfig.getForm().formVisibleStatus == Form.VISIBLE_STATUS_ORGANIZATION) {
            radioButton = view.findViewById(R.id.form_visible_status_zu_zhi);
            radioButton.setChecked(true);
//            LogUtils.d("加载-组织内可见");
        } else if (formConfig.getForm().formVisibleStatus == Form.VISIBLE_STATUS_SELF) {
            radioButton = view.findViewById(R.id.form_visible_status_self);
            radioButton.setChecked(true);
//            LogUtils.d("加载-仅自己可见");
        } else {
            radioButton = view.findViewById(R.id.form_visible_status_all);
            radioButton.setChecked(true);
            formConfig.getForm().formVisibleStatus = Form.VISIBLE_STATUS_ALL;
//            LogUtils.d("加载-所有人可见");
        }

        //设置改变事件
        visibleStatus.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.form_visible_status_zu_zhi) {
                    formConfig.getForm().formVisibleStatus = Form.VISIBLE_STATUS_ORGANIZATION;
//                    LogUtils.d("事件-组织内可见");
                } else if (checkedId == R.id.form_visible_status_self){
                    formConfig.getForm().formVisibleStatus = Form.VISIBLE_STATUS_SELF;
//                    LogUtils.d("事件-仅自己可见");
                } else if (checkedId == R.id.form_visible_status_all){
                    formConfig.getForm().formVisibleStatus = Form.VISIBLE_STATUS_ALL;
//                    LogUtils.d("事件-所有人可见");
                }
            }
        });
    }

    /**
     * 处理表单模型保存模式
     * @param view view
     */
    private void handleSaveModelPosition(View view){
        //加载原始或者传入数据
        RadioButton radioButton;
        if (formConfig.getForm().saveModelPosition == Form.SAVE_MODEL_POSITION_LOCAL) {
            radioButton = view.findViewById(R.id.form_save_model_position_local);
            radioButton.setChecked(true);
//            LogUtils.d("加载-保存本地");
        } else if (formConfig.getForm().saveModelPosition == Form.SAVE_MODEL_POSITION_SERVER) {
            radioButton = view.findViewById(R.id.form_save_model_position_server);
            radioButton.setChecked(true);
//            LogUtils.d("加载-保存服务器");
        } else {
            radioButton = view.findViewById(R.id.form_save_model_position_local);
            radioButton.setChecked(true);
            formConfig.getForm().saveModelPosition = Form.SAVE_MODEL_POSITION_LOCAL;
//            LogUtils.d("加载-保存本地");
        }

        //设置选择改变事件
        saveModelPosition.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.form_save_model_position_local) {
                    formConfig.getForm().saveModelPosition = Form.SAVE_MODEL_POSITION_LOCAL;
//                    LogUtils.d("事件-保存本地");
                } else if (checkedId == R.id.form_save_model_position_server){
                    formConfig.getForm().saveModelPosition = Form.SAVE_MODEL_POSITION_SERVER;
//                    LogUtils.d("事件-保存服务器");
                }
            }
        });
    }

    /**
     * 选择可提交人员
     */
    private void getCanSubmitPerson(){
        List<String> adminString = new ArrayList<>();

        //增加已选择的人员
        for (FormUser formUser : formConfig.getFormUserList()) {
            adminString.add(formUser.userId);
        }
        //增加已选择的部门
        for (FormFilled formFilled : formConfig.getFormFilledList()) {
            adminString.add(formFilled.BMId);
        }

        getPerson("选择可见人员",new ISelectProcessPerson() {
            @Override
            public void onOver(List<TreeMode> treeModeList) {
                //清空
                formConfig.getFormFilledList().clear();
                formConfig.getFormUserList().clear();
                StringBuilder stringBuilder = new StringBuilder();
                //筛选
                for (TreeMode treeMode : treeModeList) {
                    if (treeMode.type == TreeMode.DATA_TYPE_MU_LU) {
                        FormFilled formFilled = new FormFilled(form.id,treeMode.dataId);
                        formConfig.getFormFilledList().add(formFilled);
                    } else {
                        FormUser formUser = new FormUser(form.id,treeMode.dataId);
                        formConfig.getFormUserList().add(formUser);
                    }
                    stringBuilder.append(treeMode.name).append(",");
                }
                canSubmitPerson.setText(stringBuilder);
            }
        },adminString,true,false);
    }

    private void getAdmin(){

        //增加已选择的人员
        List<String> adminString = new ArrayList<>();
        for (FormAdmin admin : formConfig.getFormAdminList()) {
            adminString.add(admin.userId);
        }

        getPerson("选择管理员",new ISelectProcessPerson() {
            @Override
            public void onOver(List<TreeMode> treeModeList) {
                //清空
                formConfig.getFormAdminList().clear();
                StringBuilder stringBuilder = new StringBuilder();
                //筛选
                for (TreeMode treeMode : treeModeList) {
                    if (treeMode.type == TreeMode.DATA_TYPE_DATA) {
                        FormAdmin formAdmin = new FormAdmin(form.id,treeMode.dataId);
                        formConfig.getFormAdminList().add(formAdmin);
                    }
                    stringBuilder.append(treeMode.name).append(",");
                }
                formAdmin.setText(stringBuilder);
            }
        },adminString,false,false);
    }


    private void setCanSubmit(){
        if (FormBuilder.getInstance().getTreeModeList() == null) return;
        StringBuilder stringBuilder = new StringBuilder();

        if (!formConfig.getFormUserList().isEmpty() || !formConfig.getFormFilledList().isEmpty()) {
            sCanSubmitLoading.setVisibility(View.VISIBLE);
            FormBuilder.getInstance().resultTreeModeList(new IGetServerPersonResult() {
                @Override
                public void result(List<TreeMode> treeModeList) {
                    Map<String,TreeMode> allPerson = new HashMap<>();
                    if (treeModeList != null) {
                        for (TreeMode treeMode : treeModeList) {
                            allPerson.put(treeMode.dataId,treeMode);
                        }
                    }
                    for (FormUser formUser : formConfig.getFormUserList()) {
                        TreeMode treeMode = allPerson.get(formUser.userId);
                        if (treeMode != null) {
                            stringBuilder.append(treeMode.name).append(",");
                        }
                    }
                    for (FormFilled formFilled : formConfig.getFormFilledList()) {
                        TreeMode treeMode = allPerson.get(formFilled.BMId);
                        if (treeMode != null) {
                            stringBuilder.append(treeMode.name).append(",");
                        }
                    }
                    canSubmitPerson.setText(stringBuilder);
                    sCanSubmitLoading.setVisibility(View.GONE);
                }
            });
        }
    }

    private void setAdmin(){

        List<FormAdmin> formAdminList = formConfig.getFormAdminList();
        if (formAdminList != null) {
            sAdminLoading.setVisibility(View.VISIBLE);
            StringBuilder stringBuilder = new StringBuilder();
            FormBuilder.getInstance().resultTreeModeList(new IGetServerPersonResult() {
                @Override
                public void result(List<TreeMode> treeModeList) {
                    Map<String,TreeMode> allPerson = new HashMap<>();
                    if (treeModeList != null) {
                        for (TreeMode treeMode : treeModeList) {
                            allPerson.put(treeMode.dataId,treeMode);
                        }
                    }
                    for (FormAdmin admin : formAdminList) {
                        TreeMode treeMode = allPerson.get(admin.userId);
                        if (treeMode != null) {
                            stringBuilder.append(treeMode.name).append(",");
                        }
                    }
                    formAdmin.setText(stringBuilder);
                    sAdminLoading.setVisibility(View.GONE);
                }
            });

        }
    }

    /**
     * 选择表单图标
     */
    View.OnClickListener selectIcon = v -> {
        SelectFormIconDialog selectFormIconDialog = new SelectFormIconDialog(context, formIconList, new ISelectFormIcon() {
            @Override
            public void complete(FormIcon iconUrl) {
                form.icon = iconUrl.id;
                ImageUtils.loadImage(context,iconUrl.url,icon);
            }

            @Override
            public void cancel() {}
        });
        selectFormIconDialog.show();
    };

    /**
     * 选择表单类型
     */
    View.OnClickListener selectFormGroup = v -> {
        OptionPicker optionPicker = new OptionPicker(ActivityUtils.getTopActivity());
        optionPicker.setData(formGroupList);
        optionPicker.getWheelLayout().getWheelView().setFormatter(item -> ((FormGroup)item).name);
        optionPicker.setTitle("请选择表单类型");
        optionPicker.setOnOptionPickedListener(new OnOptionPickedListener() {
            @Override
            public void onOptionPicked(int position, Object item) {
                mEtGroup.setText(((FormGroup)item).name);
                form.groupId = ((FormGroup)item).id;
            }
        });
        optionPicker.show();
    };

    private void getPerson(String treeViewName,ISelectProcessPerson iSelectProcessPerson,List<String> selectedList,boolean cnSelectBuMen,boolean onlySelectBuMen){
        //人员选择dialog
        SelectPersonNewDialog newDialog = new SelectPersonNewDialog(context, treeViewName, selectedList, 0, cnSelectBuMen, onlySelectBuMen, new ISelectProcessPerson() {
            @Override
            public void onOver(List<TreeMode> treeModeList) {
                if (iSelectProcessPerson != null) iSelectProcessPerson.onOver(treeModeList);
            }
        });
        newDialog.show();
    }




    /**
     * 填写表单名称
     */
    TextWatcher writeFormName = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
        @Override
        public void afterTextChanged(Editable s) {
            form.name = s.toString();
        }
    };

    /**
     * 填写表单说明
     */
    TextWatcher writeFormNotes = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
        @Override
        public void afterTextChanged(Editable s) {
            form.notes = s.toString();
        }
    };
}
